'use strict';

const Controller = require('egg').Controller;
const fs = require('fs');
const path = require('path');
const http = require('http');

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = 'hi, egg';
  }
  
  // 主页，打包好的vue放在这里就可以
  async myPage(){
    const { ctx } = this;
    // console.log(ctx.request)
    ctx.response.type = 'html';
    ctx.body = fs.readFileSync(path.resolve(__dirname, '../public/index.html'))
  }

  // 进页面的统计，每次进来都会请求这个方法，放问量+1
  async myForm(){
    const { ctx } = this;
    const params = {
      ...ctx.request.body
    };

    let { total, sameTotal } = await ctx.service.home.getTotal();
    console.log(total, sameTotal);

    var myCookie = this.ctx.cookies.get('myCookie');
    var isAddSame = true; // 表示是否增加sameTotal，如果是同一个cookie，就不用添加

    let res = await ctx.service.home.updateTotal({ total, sameTotal }, !!myCookie);
    console.log('myres.......', res);

    // 没有myCookie，说明第一次进来
    if(!myCookie){
      myCookie = Math.random().toString(16).slice(2);
      ctx.cookies.set('myCookie', myCookie, {
        maxAge: 60*60*1000*24*365
      })
      isAddSame = false;
    }
    // console.log('xxxxxxx', this.ctx.cookies.get('myCookie'))
    ctx.body = {
      data: params.data
    }
  }

  async postTable(){
    const { ctx } = this;
    const { data } = ctx.request.body;

    let res = await ctx.service.home.submitTable();
    // console.log(res)
    if(res.affectedRows === 1){
      ctx.body = {
        data: data,
        code: 200
      }
    } else {
      ctx.body = {
        data: "接口出错",
        code: 1
      }
    }
  }

  // 获取统计信息
  async statistics(){
    const { ctx } = this;
    let res = await ctx.service.home.getAllList();

    if(res){
      
      let arrData = [
        ...res
      ]
      
      // const arrData = res;
      let res2 = await this.generateExcel(arrData);
      // console.log(res2);
      // console.log(ctx.request.origin)
      if(res2===200){
        ctx.body = {
          resMsg: res[0],
          urlLink: ctx.request.origin +'/public/info.xlsx',
          code: 200
        }
        // ctx.body = res
      }
      
    }

    console.log(res)
  }

  // 生成表格
  async generateExcel(datas){
    return new Promise((resolve, reject) => {
      const excelPort = require('excel-export');
      
      // 定义控对象，存放表头和内容，cols，rows为固定字段，不可修改
      const excelConf = {
        cols: [], // 表头
        rows: [] // 内容
      };

      var test = [ '用户', '进入网页时间', '离开网页时间', '浏览时长'];
      // 表头
      for(let key of test){

        var temp = {
          caption: key,
          type: 'string',
          width: 20,
          height: 15
        }
        excelConf.cols.push(temp)
      }
      var idx = 1;
      datas.forEach((item, index) => {
        if(item.startTime){
          const { startTime, leaveTime, diffTime } = item;
          excelConf.rows.push([(idx++).toString() , this.timeFormat(startTime), this.timeFormat(leaveTime), this.formatSeconds(diffTime/1000)])
        }
      })
      console.log(excelConf.rows);

      // 调用excelPort方法，生成最终数据
      const result = excelPort.execute(excelConf);
      // 写文件
      fs.writeFile(path.resolve(__dirname, '../public/info.xlsx'), result, 'binary', err => {
        if(!err){
          resolve(200)
        }else {
          reject(err);
        }
      })
    })
  }

  formatSeconds(value) {
    let result = Math.ceil(value)
    let h = Math.floor(result / 3600) < 10 ? '0' + Math.floor(result / 3600) : Math.floor(result / 3600);
    let m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60));
    let s = Math.floor((result % 60)) < 10 ? '0' + Math.ceil((result % 60)) : Math.ceil((result % 60));
 
    let res = '';
    if(h !== '00') res += `${h}时`;
    if(m !== '00') res += `${m}分`;
    res += `${s}秒`;
    return res;
  }

  timeFormat(time, fmt='yyyy-MM-dd h:m:s') {
    var time = new Date(time);
    var o = { 
       "M+" : time.getMonth()+1,                 //月份 
       "d+" : time.getDate(),                    //日 
       "h+" : time.getHours(),                   //小时 
       "m+" : time.getMinutes(),                 //分 
       "s+" : time.getSeconds(),                 //秒 
       "q+" : Math.floor((time.getMonth()+3)/3), //季度 
       "S"  : time.getMilliseconds()             //毫秒 
   }; 
   if(/(y+)/.test(fmt)) {
           fmt=fmt.replace(RegExp.$1, (time.getFullYear()+"").substr(4 - RegExp.$1.length)); 
   }
    for(var k in o) {
       if(new RegExp("("+ k +")").test(fmt)){
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        }
    }
   return fmt; 
  }        
  
  // 时间
  async timeOb(){
    const { ctx } = this;
    const { startTime, leaveTime, diffTime } = ctx.request.body;

    // console.log('................', startTime, leaveTime, diffTime );
    var myCookie = Math.random().toString(16).slice(2) + startTime.toString().slice(-2)
    const data = {startTime, leaveTime, diffTime, myCookie};
    let res = await ctx.service.home.timeOb(data);
    // console.log(res)
    if(res.affectedRows === 1){
      ctx.body = {
        code: 200,
        resMsg: res
      }
    } else {
      ctx.body = {
        code: 1,
        resMsg: '插入失败'
      }
    }
    
    // console.log(ctx.request)
    // ctx.body = {
      // status: 0
    // }
  }
}

module.exports = HomeController;
